<template>
  <div class="login-container">
    <div class="login-box">
      <!-- Spotify Logo -->
      <div class="logo-section">
        <div class="logo">
          <img src="/logo.png" alt="乐享作坊" width="80" height="80" class="login-logo">
        </div>
        <h1>登录到乐享作坊</h1>
      </div>



      <!-- 登录方式切换 -->
      <div class="login-methods">
        <button 
          type="button" 
          @click="switchLoginMethod('email')" 
          class="method-btn" 
          :class="{ active: loginMethod === 'email' }"
        >
          邮箱或用户名登录
        </button>
        <button 
          type="button" 
          @click="switchLoginMethod('phone')" 
          class="method-btn" 
          :class="{ active: loginMethod === 'phone' }"
        >
          使用电话号码登录
        </button>
      </div>

      <!-- 邮箱登录表单 -->
      <form v-if="loginMethod === 'email'" @submit.prevent="loginWithEmail" class="login-form">
        <div class="form-group">
          <label for="email">电子邮件或用户名</label>
          <input 
            type="text" 
            id="email" 
            v-model="form.email" 
            placeholder="电子邮件或用户名"
            required
          >
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="form.password" 
            placeholder="密码"
            required
          >
        </div>

        <div class="form-options">
          <label class="remember-me">
            <input type="checkbox" v-model="form.rememberMe">
            <span class="checkmark"></span>
            记住我
          </label>
        </div>

        <div class="form-group">
          <button type="submit" class="login-btn" :disabled="loading || !isEmailFormValid">
            <span v-if="loading" class="loading-spinner"></span>
            <span v-else>登录</span>
          </button>
        </div>

      </form>

      <!-- 手机号登录表单 -->
      <form v-if="loginMethod === 'phone'" @submit.prevent="loginWithPhone" class="login-form">
        <div class="form-group">
          <label for="phone">手机号码</label>
          <input 
            type="tel" 
            id="phone" 
            v-model="phoneForm.phone" 
            placeholder="请输入手机号码"
            required
          >
        </div>

        <div class="form-group" v-if="!showVerificationCode">
          <button type="button" @click="sendVerificationCode" class="send-code-btn" :disabled="!isPhoneValid">
            发送验证码
          </button>
        </div>

        <div class="form-group" v-if="showVerificationCode">
          <label for="verification-code">验证码</label>
          <div class="verification-input">
            <input 
              type="text" 
              id="verification-code" 
              v-model="phoneForm.verificationCode" 
              placeholder="请输入4位验证码"
              maxlength="4"
              required
            >
            <span class="generated-code">验证码: {{ generatedCode }}</span>
          </div>
          <button type="button" @click="sendVerificationCode" class="resend-btn" :disabled="countdown > 0">
            重新发送 {{ countdown > 0 ? `(${countdown}s)` : '' }}
          </button>
        </div>

        <div class="form-options" v-if="showVerificationCode">
          <label class="remember-me">
            <input type="checkbox" v-model="phoneForm.rememberMe">
            <span class="checkmark"></span>
            记住我
          </label>
        </div>

        <div class="form-group">
          <button type="submit" class="login-btn" :disabled="loading || !isPhoneFormValid">
            <span v-if="loading" class="loading-spinner"></span>
            <span v-else>验证并登录</span>
          </button>
        </div>

      </form>



      <div class="signup-link">
        <span>还没有账号？</span>
        <router-link to="/users/register" class="signup-btn">前往注册</router-link>
      </div>

    </div>

    <!-- 注册提示对话框 -->
    <div v-if="showRegisterDialog" class="modal-overlay" @click="showRegisterDialog = false">
      <div class="register-dialog" @click.stop>
        <div class="dialog-header">
          <h3>账户未注册</h3>
          <button @click="showRegisterDialog = false" class="close-btn">×</button>
        </div>
        <div class="dialog-content">
          <p>{{ registerDialogMessage }}</p>
          <p>您可以前往注册页面创建新账户</p>
        </div>
        <div class="dialog-actions">
          <button @click="showRegisterDialog = false" class="cancel-btn">取消</button>
          <button @click="goToRegister" class="confirm-btn">前往注册</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginView',
  data() {
    return {
      loginMethod: 'email', // 'email' 或 'phone'
      form: {
        email: '',
        password: '',
        rememberMe: false
      },
      phoneForm: {
        phone: '',
        verificationCode: '',
        rememberMe: false
      },
      showVerificationCode: false,
      countdown: 0,
      countdownTimer: null,
      generatedCode: '', // 从后端获取的验证码（开发用）
      showRegisterDialog: false,
      registerDialogMessage: '',
      loading: false
    }
  },
  computed: {
    isEmailFormValid() {
      return this.form.email.trim() && this.form.password.trim();
    },
    isPhoneValid() {
      // 简单的手机号验证（11位数字）
      return /^1[3-9]\d{9}$/.test(this.phoneForm.phone);
    },
    isPhoneFormValid() {
      return this.phoneForm.verificationCode.length === 4 && this.isPhoneValid;
    }
  },
  methods: {
    switchLoginMethod(method) {
      this.loginMethod = method;
      // 切换时重置表单状态
      if (method === 'phone') {
        this.showVerificationCode = false;
        this.phoneForm.verificationCode = '';
        this.generatedCode = '';
        this.countdown = 0;
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
        }
      }
    },
    
    async loginWithEmail() {
      try {
        if (!this.isEmailFormValid) {
          this.$root.showToast('请填写完整的登录信息', 'warning');
          return;
        }
        
        // 判断输入的是邮箱还是用户名
        const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.form.email);
        const loginField = isEmail ? 'email' : 'username';
        
        const loginData = {
          emailOrUsername: this.form.email,
          password: this.form.password,
          rememberMe: this.form.rememberMe
        };
        
        console.log(`${isEmail ? '邮箱' : '用户名'}登录:`, loginData);
        
        // TODO: 调用后端API进行登录验证
        // const response = await api.login(loginData);
        
        // 调用后端API进行登录验证
        const response = await this.$http.post('/api/users/login', loginData);
        
        console.log('登录响应原始数据:', response);
        console.log('登录响应类型:', typeof response);
        console.log('response.success:', response.success);
        console.log('response.token:', response.token);
        console.log('response.user:', response.user);
        
        if (response.success) {
          console.log('登录成功，设置登录状态');
          
          // 设置前台用户登录状态 - 使用独立的key
          localStorage.setItem('userToken', response.token);
          localStorage.setItem('userId', response.user.userId);
          localStorage.setItem('username', response.user.username);
          localStorage.setItem('userEmail', response.user.email);
          
          // 计算token过期时间
          const expiryHours = this.form.rememberMe ? 24 * 7 : 24; // 记住我7天，否则24小时
          const expiryTime = Date.now() + (expiryHours * 60 * 60 * 1000);
          localStorage.setItem('userTokenExpiry', expiryTime.toString());
          
          // 保存完整的用户信息
          if (response.user) {
            localStorage.setItem('userInfo', JSON.stringify(response.user));
          }
          
          console.log('登录状态保存完成');
          
          this.$root.showToast('登录成功！', 'success');
          
          // 通知App.vue刷新登录状态
          if (this.$root.refreshLoginStatus) {
            console.log('刷新登录状态');
            await this.$root.refreshLoginStatus();
          }
          
          this.$router.push('/');
        } else {
          console.log('登录失败:', response.message);
          this.handleLoginError(response.message || '登录失败');
        }
      } catch (error) {
        console.error('登录失败:', error);
        const errorMessage = error.response?.data?.message || '登录失败，请检查您的网络连接';
        this.handleLoginError(errorMessage);
      }
    },
    
    async sendVerificationCode() {
      if (!this.isPhoneValid) {
        this.$root.showToast('请输入正确的手机号码', 'warning');
        return;
      }

      // 检查是否在倒计时期间
      if (this.countdown > 0) {
        this.$root.showToast(`请等待 ${this.countdown} 秒后再重新发送`, 'warning');
        return;
      }
      
      try {
        // 调用后端API发送验证码
        const response = await this.$http.post('/api/users/send-code', null, {
          params: { phone: this.phoneForm.phone }
        });
        
        if (response.success) {
          this.showVerificationCode = true;
          this.phoneForm.verificationCode = '';
          
          // 获取验证码（开发环境显示）
          if (response.verificationCode) {
            this.generatedCode = response.verificationCode;
          }
          
          // 开始倒计时
          this.countdown = 60;
          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
            }
          }, 1000);
          
          this.$root.showToast(`验证码已发送到 ${this.phoneForm.phone}`, 'success');
        } else {
          this.$root.showToast(response.message || '发送验证码失败', 'error');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        const errorMessage = error.response?.data?.message || '发送验证码失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },
    
    async loginWithPhone() {
      try {
        if (!this.isPhoneFormValid) {
          this.$root.showToast('请填写完整的手机号和验证码', 'warning');
          return;
        }
        
        const phoneLoginData = {
          phone: this.phoneForm.phone,
          verificationCode: this.phoneForm.verificationCode,
          rememberMe: this.phoneForm.rememberMe
        };
        
        // 调用后端API进行手机号登录验证
        const response = await this.$http.post('/api/users/login/phone', phoneLoginData);
        
        console.log('手机号登录响应原始数据:', response);
        console.log('手机号登录响应类型:', typeof response);
        console.log('response.success:', response.success);
        console.log('response.token:', response.token);
        console.log('response.user:', response.user);
        
        if (response.success) {
          console.log('手机号登录成功，设置登录状态');
          
          // 设置前台用户登录状态 - 使用独立的key
          localStorage.setItem('userToken', response.token);
          localStorage.setItem('userId', response.user.userId);
          localStorage.setItem('username', response.user.username);
          localStorage.setItem('userEmail', response.user.email);
          
          // 计算token过期时间
          const expiryHours = this.phoneForm.rememberMe ? 24 * 7 : 24; // 记住我7天，否则24小时
          const expiryTime = Date.now() + (expiryHours * 60 * 60 * 1000);
          localStorage.setItem('userTokenExpiry', expiryTime.toString());
          
          // 保存完整的用户信息
          if (response.user) {
            localStorage.setItem('userInfo', JSON.stringify(response.user));
          }
          
          console.log('手机号登录状态保存完成');
          
          this.$root.showToast('登录成功！', 'success');
          
          // 通知App.vue刷新登录状态
          if (this.$root.refreshLoginStatus) {
            console.log('刷新登录状态');
            await this.$root.refreshLoginStatus();
          }
          
          this.$router.push('/');
        } else {
          console.log('手机号登录失败:', response.message);
          this.handleLoginError(response.message || '登录失败');
        }
      } catch (error) {
        console.error('手机号登录失败:', error);
        const errorMessage = error.response?.data?.message || '登录失败，请检查您的网络连接';
        this.handleLoginError(errorMessage);
      }
    },
    
    forgotPassword() {
      // TODO: 实现忘记密码功能
      console.log('忘记密码');
    },

    handleLoginError(errorMessage) {
      // 检查是否是未注册的错误
      if (errorMessage.includes('未注册')) {
        this.showRegisterPrompt(errorMessage);
      } else {
        this.$root.showToast(errorMessage, 'error');
      }
    },

    showRegisterPrompt(message) {
      // 显示自定义注册提示对话框
      this.registerDialogMessage = message;
      this.showRegisterDialog = true;
    },

    goToRegister() {
      this.showRegisterDialog = false;
      this.$router.push('/users/register');
    },


  },
  
  beforeUnmount() {
    // 清理倒计时定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
}

.login-box {
  background: #121212;
  border-radius: 8px;
  padding: 48px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 4px 60px rgba(0, 0, 0, 0.5);
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  margin-bottom: 16px;
}

.login-logo {
  border-radius: 8px;
  transition: all 0.2s ease;
}

.login-logo:hover {
  transform: scale(1.1);
}

.logo-section h1 {
  color: white;
  font-size: 48px;
  font-weight: 700;
  margin: 0;
  letter-spacing: -0.04em;
}



/* 登录方式切换 */
.login-methods {
  display: flex;
  background: #121212;
  border-radius: 500px;
  padding: 4px;
  margin-bottom: 24px;
  border: 1px solid #727272;
}

.method-btn {
  flex: 1;
  background: transparent;
  border: none;
  color: #b3b3b3;
  font-size: 14px;
  font-weight: 700;
  padding: 12px 16px;
  border-radius: 500px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.method-btn.active {
  background: #1db954;
  color: #000;
}

.method-btn:hover:not(.active) {
  color: #ffffff;
}

.login-form {
  margin-bottom: 32px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  color: white;
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 8px;
}

.form-group input {
  width: 100%;
  height: 48px;
  background: #121212;
  border: 1px solid #727272;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  padding: 0 12px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: white;
}

.form-group input::placeholder {
  color: #727272;
}

.form-options {
  margin-bottom: 32px;
}

.remember-me {
  display: flex;
  align-items: center;
  color: white;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
}

.remember-me input {
  display: none;
}

.checkmark {
  width: 16px;
  height: 16px;
  border: 1px solid #727272;
  border-radius: 2px;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.remember-me input:checked + .checkmark {
  background: #1db954;
  border-color: #1db954;
}

.remember-me input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.login-btn {
  width: 100%;
  height: 48px;
  background: #1db954;
  border: none;
  border-radius: 500px;
  color: black;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.login-btn:hover:not(:disabled) {
  background: #1ed760;
  transform: scale(1.02);
}

.login-btn:disabled {
  background: #535353;
  cursor: not-allowed;
  transform: none;
}

/* 手机号登录相关样式 */
.send-code-btn {
  width: 100%;
  height: 48px;
  background: #1db954;
  border: none;
  border-radius: 4px;
  color: black;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-code-btn:hover:not(:disabled) {
  background: #1ed760;
}

.send-code-btn:disabled {
  background: #535353;
  cursor: not-allowed;
}

.verification-input {
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
}

.verification-input input {
  flex: 1;
}

.generated-code {
  background: rgba(29, 185, 84, 0.1);
  border: 1px solid #1db954;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 12px;
  color: #1db954;
  font-weight: 700;
  white-space: nowrap;
}

.resend-btn {
  background: none;
  border: 1px solid #727272;
  border-radius: 4px;
  color: #b3b3b3;
  font-size: 12px;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 8px;
}

.resend-btn:hover:not(:disabled) {
  border-color: #1db954;
  color: #1db954;
}

.resend-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  border-color: #535353;
  color: #535353;
}



.signup-link {
  text-align: center;
  margin-bottom: 32px;
}

.signup-link span {
  color: #727272;
  font-size: 16px;
  margin-right: 4px;
}

.signup-btn {
  color: white;
  font-size: 16px;
  text-decoration: underline;
  transition: color 0.3s ease;
}

.signup-btn:hover {
  color: #1db954;
}


/* 注册提示对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.register-dialog {
  background: #181818;
  border-radius: 8px;
  width: 90%;
  max-width: 450px;
  overflow: hidden;
  animation: slideIn 0.3s ease;
  border: 1px solid #333;
}

.dialog-header {
  padding: 20px 24px;
  border-bottom: 1px solid #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.dialog-content {
  padding: 24px;
  color: #b3b3b3;
  line-height: 1.5;
}

.dialog-content p {
  margin: 0 0 12px 0;
}

.dialog-content p:last-child {
  margin-bottom: 0;
}

.dialog-actions {
  padding: 16px 24px 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
}

.cancel-btn {
  background: transparent;
  color: #b3b3b3;
  border: 1px solid #535353;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-color: #727272;
}

.confirm-btn {
  background: #1db954;
  color: black;
}

.confirm-btn:hover {
  background: #1ed760;
  transform: scale(1.02);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { 
    opacity: 0;
    transform: translateY(-20px);
  }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 16px;
  }
  
  .login-box {
    padding: 24px;
  }
  
  .logo-section h1 {
    font-size: 32px;
  }
}
</style> 